package cn.xiangxu.demo.sell_demo.service.impl;

import cn.xiangxu.demo.sell_demo.entity.entityDTO.OrderDTO;
import cn.xiangxu.demo.sell_demo.enums.ResultEnum;
import cn.xiangxu.demo.sell_demo.exceptions.SellException;
import cn.xiangxu.demo.sell_demo.service.BuyerService;
import cn.xiangxu.demo.sell_demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("buyerService")
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancelOrderOne(String openid, String orderId) {
        // 01 获取订单
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);

        // 02 订单非空判断
        if (orderDTO == null) {
            log.error("【取消订单】-查询不到该订单-orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    public OrderDTO checkOrderOwner(String openid, String orderId) {
        // 01 根据订单ID查询订单信息
        OrderDTO orderDTO = orderService.findByOrderId(orderId);

        // 02 判断订单是否为空
        if (orderDTO == null) {
            return null;
        }

        // 03 判断是否是自己的订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】-openid不一致，openid={}, orderDTO={}", openid, orderDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }

        // 04 返回订单详情
        return orderDTO;
    }
}
